﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Audio;

namespace MagicWand
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;

        Vector2 tapPosition;
        Vector2 sparkPosition;
        Vector2 wandPosition;
        UIElementRenderer elementRenderer;
        Texture2D sparks;
        Texture2D wand;

        List<BurstEffect> effects = new List<BurstEffect>();

        SoundEffect wandSound;
        SoundEffectInstance instance;
        bool isTapping = false;

        TimeSpan timeToChangeColor;
        Color currentColor;
        int colorIndex;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;            

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            timeToChangeColor = TimeSpan.FromSeconds(5);
            colorIndex = 0;
            currentColor = Color.White;            

            // Use the LayoutUpdate event to know when the page layout 
            // has completed so that we can create the UIElementRenderer.
            LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            if (sparks == null)
            {
                sparks = contentManager.Load<Texture2D>("effectparticle");
            }
            wand = contentManager.Load<Texture2D>("wand");
            wandSound = contentManager.Load<SoundEffect>("soundeffect");
            instance = wandSound.CreateInstance();
            instance.IsLooped = true;

            sparkPosition = new Vector2((SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2), 200);
            wandPosition = new Vector2((SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2 - wand.Bounds.Width / 2), 200);
            if (elementRenderer == null)
                elementRenderer = new UIElementRenderer(this, (int)SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width,
                    (int)SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Height);

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            timeToChangeColor -= e.ElapsedTime;
            if (timeToChangeColor <= TimeSpan.Zero)
            {
                if (colorIndex == 0)
                {
                    colorIndex = 1;
                    currentColor = Color.Yellow;
                }
                else if (colorIndex == 1)
                {
                    colorIndex = 2;
                    currentColor = Color.Orange;
                }
                else if (colorIndex == 2)
                {
                    colorIndex = 3;
                    currentColor = Color.Red;
                }
                else if (colorIndex == 3)
                {
                    colorIndex = 4;
                    currentColor = Color.Purple;
                }
                else if (colorIndex == 4)
                {
                    colorIndex = 5;
                    currentColor = Color.Blue;
                }
                else if (colorIndex == 5)
                {
                    colorIndex = 6;
                    currentColor = Color.DarkSeaGreen;
                }
                else if (colorIndex == 6)
                {
                    colorIndex = 7;
                    currentColor = Color.Green;
                }
                else
                {
                    colorIndex = 0;
                    currentColor = Color.YellowGreen;
                }

                timeToChangeColor = TimeSpan.FromSeconds(5);
            }

            TouchCollection touchCollection = TouchPanel.GetState();
            if (touchCollection.Count > 0)
            {
                foreach (TouchLocation tl in touchCollection)
                {
                    if ((tl.State == TouchLocationState.Pressed) || (tl.State == TouchLocationState.Moved))
                    {
                        tapPosition = sparkPosition;
                        isTapping = true;
                        addLineEffect(tapPosition);
                    }
                }
            }
            else
            {
                isTapping = false;
            }

            for (int i = 0; i < effects.Count; i++)
            {
                effects[i].Update(e);
                if (effects[i].Finished)
                {
                    effects.RemoveAt(i);
                    i--;
                }
            }

            if (isTapping)
            {
                if (instance.State.Equals(SoundState.Paused) || instance.State.Equals(SoundState.Stopped))
                {
                    instance.Play();
                }
            }
            else
            {
                instance.Pause();
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.Black);

            // TODO: Add your drawing code here
            // Render the Silverlight controls using the UIElementRenderer.
            elementRenderer.Render();

            spriteBatch.Begin();
            // Using the texture from the UIElementRenderer, 
            // draw the Silverlight controls to the screen.
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            spriteBatch.Draw(wand, wandPosition, Color.White);

            foreach (BurstEffect effect in effects)
            {
                effect.Draw(spriteBatch, currentColor);
            }            

            spriteBatch.End();
        }

        void GamePage_LayoutUpdated(object sender, EventArgs e)
        {
            // Create the UIElementRenderer to draw the XAML page to a texture.

            // Check for 0 because when we navigate away the LayoutUpdate event
            // is raised but ActualWidth and ActualHeight will be 0 in that case.
            if ((ActualWidth > 0) && (ActualHeight > 0))
            {
                SharedGraphicsDeviceManager.Current.PreferredBackBufferWidth = (int)ActualWidth;
                SharedGraphicsDeviceManager.Current.PreferredBackBufferHeight = (int)ActualHeight;
            }

            if (null == elementRenderer)
            {
                elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
            }
        }

        public void addLineEffect(Vector2 newPosition)
        {
            List<Texture2D> textureList = new List<Texture2D>();
            textureList.Add(sparks);
            Random random = new Random();
            effects.Add(new BurstEffect(textureList, newPosition, newPosition, new Vector2(-7, -7), new Vector2(7, 7), -0.05f, -0.05f, -0.05f, .05f, 40, 100, 1, 5, new Vector2(1, 1), new Vector2(1.5f, 1), random));
        }
    }
}